import sys
import os
from pydantic import BaseModel

class Pyshell_model(BaseModel):
    data: str

def pyShell(pyShell_codes):
    pyShell_codes = pyShell_codes.data
    pyShell_codes = pyShell_codes.split('\n')
    pyShell_stdo = sys.stdout
    pyShell_filename = 'out.txt'
    with open(pyShell_filename, 'w+') as pyShell_f:
        sys.stdout = pyShell_f
        for pyShell_i in range(len(pyShell_codes)):
            try: exec(pyShell_codes[pyShell_i])
            except Exception as pyShell_e:
                print("in line " + str(pyShell_i + 1) + ", " + str(pyShell_e.args[0]))
                break

    with open(pyShell_filename) as pyShell_f:
        pyShell_result = pyShell_f.read()

    os.remove(pyShell_filename)
    sys.stdout = pyShell_stdo
    return {'data': pyShell_result}

if __name__ == '__main__':
    codes = '''from sympy import *
x = symbols('x')
a = Eq(2*x**2 + 7, 0)

b = solve(a, x)
print(b)
print(latex(b))
'''
    codes = {'data': codes}
    b = pyShell(codes)
    print(b)
